const {ccclass, property} = cc._decorator;

@ccclass
export default class CameraFollow extends cc.Component {
    /** 摄像机跟随的目标 */
    private target:cc.Node;
    /** 设像机跟随范围 */
    private range:cc.Size;

    private startFollow:boolean=false;


    @property()
    smoothFollow:boolean=false;
    @property()
    followX:number=0;
    @property()
    followY:number=0;
    @property()
    followRatio:number=0;
    @property()    
    minFollowDist:number=0;


    lateUpdate() {
        if(!this.target) return;
        let targetPos = this.target.position;


        
        this.node.position = targetPos;
       

    
 

        if(targetPos.x>this.range.width){
            this.node.x = this.range.width
        }
        if(targetPos.x<-this.range.width){
            this.node.x = -this.range.width;
        } 
        if(targetPos.y>this.range.height){
            this.node.y = this.range.height;
        } 
        if(targetPos.y<-this.range.height){
            this.node.y = -this.range.height;
        } 
    }



    follow(node:cc.Node,rect:cc.Size){
        this.target = node;
        var gameSize = cc.winSize;
        var w = (rect.width-gameSize.width)/2;
        var h = (rect.height-gameSize.height)/2;
        this.range = cc.size(w,h);        
    }

    /** 截图 */
    Screenshot(node:cc.Node){
        var camera = this.getComponent(cc.Camera);
        
        let texture = new cc.RenderTexture();
        var width = cc.winSize.width;
        var height = cc.winSize.height;
        texture.initWithSize(width,height);
        camera.targetTexture = texture;
        camera.render(node);
        let data = texture.readPixels();
        let canvas = document.createElement("canvas");
        let ctx = canvas.getContext("2d");
        canvas.width = texture.width;
        canvas.height = texture.height;        
        let rowBytes = canvas.width*4;
        for(let row=0;row<height;row++){
            let srow = height-1-row;
            let imageData = ctx.createImageData(width,1);
            let start = srow*width*4;
            for(let i=0;i<rowBytes;i++){
                imageData.data[i] = data[start+i];
            }
            ctx.putImageData(imageData,0,row);
        }
        let dataURL = canvas.toDataURL("image/jpeg");
        
        camera.targetTexture = null;
        console.log(dataURL);
    }

}
